// store.modules.user.js
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login as apiLogin, getUserInfo } from '@/api/user'

const state = {
  token: getToken() || '',  // 确保token总是字符串
  user: null
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    // 如果需要立即存储token
    if (token) setToken(token)
    else removeToken()
  },
  SET_USER(state, user) {
    state.user = user || {}
  },
  CLEAR_ALL(state) {
    state.token = ''
    state.user = {}
    removeToken()
  }
}

const actions = {
  async login({ commit }, { token, remember }) {
    try {
      commit('SET_TOKEN', token)
      
      // 如果需要记住登录状态
      if (remember) {
        setToken(token) // 调用工具函数持久化token
      }
      
      // 获取用户信息
      const userInfo = await getUserInfo()
      commit('SET_USER', userInfo.data)
      
      return userInfo
    } catch (error) {
      commit('CLEAR_ALL')
      throw error
    }
  },
  
  async getInfo({ commit }) {
    try {
      const response = await getUserInfo()
      commit('SET_USER', response.data)
      return response
    } catch (error) {
      commit('SET_USER', {})
      throw error
    }
  },
  
  logout({ commit }) {
    commit('CLEAR_ALL')
  }
}

const getters = {
  isAuthenticated: state => {
    if (!state) {  // 防御state为null的情况
      console.error('Vuex state is null in user module')
      return false
    }
    return !!state.token
  },
  currentUser: state => {
    if (!state) {  // 防御state为null的情况
      console.error('Vuex state is null in user module')
      return {}
    }
    return state.user || {}
  },
  token: state => {
    if (!state) {  // 防御state为null的情况
      console.error('Vuex state is null in user module')
      return ''
    }
    return state.token
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}